package cn.com.lms.business.exam.web;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.exam.persistence.entity.Question;

import cn.com.lms.business.exam.persistence.entity.QuestionVO;
import cn.com.lms.business.exam.service.QuestionCategoryService;
import cn.com.lms.business.exam.service.QuestionService;


import cn.com.lms.business.exam.service.QuestionSubjectService;
import cn.com.lms.business.log.enums.ActionTypeEnum;
import cn.com.lms.business.log.persistence.entity.UserActionLog;
import cn.com.lms.business.user.persistence.entity.SysUserVo;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;


import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;

import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zhangzhenjiang
 * @createDate 2020/3/14
 * @description
 */
@Tag(name = "题库", description = "题库管理")
@RestController
@RequestMapping("/exam/question")
public class QuestionController {

    @Autowired
    QuestionService questionService;

    @Autowired
    QuestionSubjectService questionSubjectService;

    @Autowired
    QuestionCategoryService questionCategoryService;

    @Operation(summary = "分页查询", description = "题库分页查询", parameters = {
            @Parameter(name = "keyWord", description = "题库名称", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "String", description = "课程标题")),
            @Parameter(name = "categoryId", description = "分类id", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "String", description = "课程目录id")),
            @Parameter(name = "isGreeterThanZero", description = "题目数是否大于0", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "String", description = "题目数是否大于0")),
            @Parameter(name = "limit", description = "分页大小", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "分页大小")),
            @Parameter(name = "offset", description = "页码", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "页码")),
    })
    @GetMapping(value = "/page")
    public ResponseResult<Page<QuestionVO>> getQuestionPage(HttpServletRequest request) {
        String keyWord = request.getParameter("keyWord");
        String categoryId = request.getParameter("CategoryId");
        //
        String isGreeterThanZero = request.getParameter("isGreeterThanZero");


        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "eq.create_time"));
        String whereCoutSQL=" ";
        if (!StringUtils.isEmpty(isGreeterThanZero) && isGreeterThanZero.equals("true")) {
            whereCoutSQL = " and (select count(1) from bnz_exam_question_subject qs where qs.question_id=eq.id and qs.is_delete=0) >0 ";
        }
         QueryHelpBean queryHelpBean = QuestionService.getQueryHelpBean(whereCoutSQL);
        queryHelpBean.setPageable(pageable);
        IExpression andCondition1 = CompareExpression.build("eq.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(andCondition1);


        if (!StringUtils.isEmpty(keyWord)) {
            IExpression andCondition2 = CompareExpression.build("eq.question_name", CompareType.like, keyWord);
            queryHelpBean.addWhere(andCondition2);
        }

        if (!StringUtils.isEmpty(categoryId) && !categoryId.equals(0)) {

            List<Long> childrenIds = questionCategoryService.findChildrenIds(Long.valueOf(categoryId));

            childrenIds.add(Long.valueOf(categoryId));
            IExpression andCondition3 = CompareExpression.build("eq.category_id", CompareType.in, childrenIds);
            queryHelpBean.addWhere(andCondition3);
        }
        Page<QuestionVO> all = questionService.findAll(queryHelpBean);

        return ResponseResult.success(all);
    }

    @Operation(summary = "根据id查询")
    @GetMapping("/one/{id}")
    public ResponseResult<Map> getById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Map question = questionService.findQuestionById(id);
        if (question==null) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        return ResponseResult.success(question);
    }


    @Operation(summary = "保存")
    @PostMapping("/save")
    public ResponseResult<?> addQuestion(@RequestBody Question question) {
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        question.setCreator(String.valueOf(sysUser.getId()));
        question.setCreateTime(new Date());
        question.setCreatorName(sysUser.getCname());
        question.setIsDelete(false);
        question.setIsPrivate(false);
        questionService.save(question);
        return ResponseResult.success();
    }


    @Operation(summary = "更新")
    @PostMapping("/update")
    public ResponseResult<?> updateQuestion(@RequestBody Question question) {
        if (ObjectUtils.isEmpty(question.getId())) {
            throw new BusinessException(ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getMessage(), "" + ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getCode());
        }
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        question.setModifyTime(new Date());
        question.setCreator(String.valueOf(sysUser.getId()));
        question.setCreateTime(new Date());
        question.setCreatorName(sysUser.getCname());

        questionService.updateQuestion(question);
        return ResponseResult.success();
    }

    @Operation(summary = "题库列表",description = "所有题库列表")
    @GetMapping("/list")
    public ResponseResult<List<Map>> getQuestionList(HttpServletRequest request) {

        List<Map> list= questionService.queryQuestion();
        return ResponseResult.success(list);
    }

    @Operation(summary = "删除", description = "根据分类id删除分类及子类")
    @GetMapping("/delete/{id}")
    public ResponseResult<Integer> deleteById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new BusinessException(ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getMessage(), "" + ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getCode());
        }
        List<Long> idList=new ArrayList<>();
        idList.add(id);
        List<Map<String,Object>> questionSubjectList = questionSubjectService.findMapListByQuestionIdList(idList);
        if (questionSubjectList.size() > 0) {
            throw new BusinessException(ErrorEnum.QUESTION_SUBJECT_EXIST.getMessage(), "" + ErrorEnum.QUESTION_SUBJECT_EXIST.getCode());

        }
        Integer count = questionService.updateIsDelete(true, idList);

        return ResponseResult.success(count);

    }




}
